package com.jci.vsd.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.NotificationManagerCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.github.dfqin.grantor.PermissionListener;
import com.github.dfqin.grantor.PermissionsUtil;
import com.jci.vsd.R;
import com.jci.vsd.activity.UserInfo.UserInfoActivity;
import com.jci.vsd.application.VsdApplication;
import com.jci.vsd.bean.download.CheckUpdateResponse;
import com.jci.vsd.constant.AppConstant;
import com.jci.vsd.constant.MySpEdit;
import com.jci.vsd.data.UserData;
import com.jci.vsd.fragment.EnterpriseHomeFragment;
import com.jci.vsd.fragment.HomeFragment;
import com.jci.vsd.fragment.MessageFragment;
import com.jci.vsd.network.control.DownloadAppControl;
import com.jci.vsd.observer.DefaultObserver;
import com.jci.vsd.observer.RxHelper;
import com.jci.vsd.utils.Loger;
import com.jci.vsd.utils.Utils;
import com.jci.vsd.view.BottomNavigationItem;
import com.jci.vsd.view.CircleImageView;
import com.jci.vsd.view.widget.SimpleToast;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;

// 新的主页

public class MainNewActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.button_back)
    ImageButton buttonBack;

    @BindView(R.id.tv_header)
    CircleImageView ivHeader;
    @BindView(R.id.textview_title)
    TextView tvTitle;

    private String roleType; //角色类型：1 领导 2部门主管 3 普通员工
    private String lastVersion;
    private String apkUrl;
    private MySpEdit prefs;
    private Context mContext;

    private List<BottomNavigationItem> data = new ArrayList<>();
    private HomeFragment homeFragment;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = MainNewActivity.this;
        //消息轮巡
        msgService();
        prefs = MySpEdit.getInstance();
        roleType = prefs.getRole();
        if (!TextUtils.isEmpty(roleType)) {
            if (roleType.equals("1") || roleType.equals("2")) {
                //bossor 部门领导 有公司tab
                setContentView(R.layout.activity_main_new);

            } else {
                //员工 无公司tab
                setContentView(R.layout.activity_main_employee);
            }
        }
        //setContentView后 bind
        ButterKnife.bind(this);
        tvTitle.setText(getResources().getString(R.string.home_title));
        lastVersion = Utils.getVersionName();
        buttonBack.setVisibility(View.GONE);
        ivHeader.setVisibility(View.VISIBLE);
        //检测更新
        checkUpdateApp();
        homeFragment = new HomeFragment();
        addFragmentNotToStack(R.id.search_edit_frame, homeFragment);
        BottomNavigationItem b1 = (BottomNavigationItem) findViewById(R.id.bni1);
        BottomNavigationItem b2 = (BottomNavigationItem) findViewById(R.id.bni2);
        BottomNavigationItem b3 = (BottomNavigationItem) findViewById(R.id.bni3);
        b1.setOnClickListener(this);
        b2.setOnClickListener(this);
        b3.setOnClickListener(this);
        ivHeader.setOnClickListener(this);
        data.add(b1);
        data.add(b2);
        data.add(b3);
        String type = getIntent().getStringExtra(AppConstant.KEY_TYPE);
        if (!TextUtils.isEmpty(type) && type.equals("msg")) {
            setClick(1);
            addFragmentNotToStack(R.id.search_edit_frame, new MessageFragment());
        } else {
            setClick(0);
            addFragmentNotToStack(R.id.search_edit_frame, new HomeFragment());
        }

    }


    private void setClick(int postion) {
        for (int i = 0; i < data.size(); i++) {
            if (i == postion) {
                data.get(i).setClick(true);
            } else {
                data.get(i).setClick(false);
            }

        }
    }

    private void msgService() {
        Intent serviceIntent = new Intent(MainNewActivity.this, NoticeMsgService.class);
        startService(serviceIntent);
    }

    private void checkUpdateApp() {
        Observable<CheckUpdateResponse> checkUpdateResponseObservable = new DownloadAppControl().getNewAppVersion();
        DefaultObserver<CheckUpdateResponse> checkUpdateResponseCommonDialogObserver = new DefaultObserver<CheckUpdateResponse>() {
            @Override
            protected void showProgress() {

            }

            @Override
            protected void dismissProgress() {

            }

            @Override
            public void onNext(final CheckUpdateResponse checkUpdateResponse) {
                super.onNext(checkUpdateResponse);

                if (checkUpdateResponse.isFlag()) {
                    apkUrl = checkUpdateResponse.getUrl();
                    MySpEdit.getInstance().setApkUrl(apkUrl);
                    //  apkUrl="http://www.izis.cn/mygoedu/yztv_1.apk";
                    //apkUrl="http://7xk9dj.com1.z0.glb.clouddn.com/BGAUpdateSample_v1.0.3_debug.apk";
                    lastVersion = checkUpdateResponse.getLast();
                    if (PermissionsUtil.hasPermission(mContext, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.READ_EXTERNAL_STORAGE)) {

                        // apkUrl="http://192.168.31.109:8080/shuidao/notoken/downapk";
                        //  apkUrl=  "http://download.fir.im/v2/app/install/5818acbcca87a836f50014af?download_token=a01301d7f6f8f4957643c3fcfe5ba6ff";
                        // apkUrl=   "http:\\/\\/www.pgyer.com\\/app\\/installUpdate\\/3becc83ec489185cd5a9259ffc9bef6c?sig=nkhiTi3LmGR8cArX7Ab%2BkeXfxSjZxTsZybjWdwhdwBxZPminY8nLlmO%2B48W%2FYFIA";
                        //  apkUrl= "http:\\/\\/www.pgyer.com\\/app\\/installUpdate\\/3becc83ec489185cd5a9259ffc9bef6c?sig=nkhiTi3LmGR8cArX7Ab%2BkeXfxSjZxTsZybjWdwhdwBwxwSphumXkpHvym1j7jCxc";
                        //  apkUrl="http:\\/\\/www.pgyer.com\\/app\\/installUpdate\\/3becc83ec489185cd5a9259ffc9bef6c?sig=nkhiTi3LmGR8cArX7Ab%2BkeXfxSjZxTsZybjWdwhdwByP7C554zZA33sLt2byZLnb";

                        // updateShowDialog(apkUrl, lastVersion);
                        showNoticeDialog(lastVersion);
                        MySpEdit.getInstance().setLastVersion(lastVersion);
                        Loger.e("--lastVersion--" + lastVersion);

                    } else {
                        PermissionsUtil.requestPermission(MainNewActivity.this, new PermissionListener() {
                                    @Override
                                    public void permissionGranted(@NonNull String[] permission) {
                                        Log.e("--", "permissionGranted: 用户授予了访问外部存储的权限");
                                    }

                                    @Override
                                    public void permissionDenied(@NonNull String[] permission) {
                                        Log.e("--", "permissionDenied: 用户拒绝了访问外部存储的申请");
                                        // needPermissionTips();

                                    }
                                }, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.READ_EXTERNAL_STORAGE);
                    }


                }
                MySpEdit.getInstance().setLastVersion(lastVersion);
                Loger.e("--getVersionLast--" + MySpEdit.getInstance().getLastVersion());
//                updateShowDialog(checkUpdateResponse.getUrl(), checkUpdateResponse.getLast());
//                // updateShowDialog(apkUrl, checkUpdateResponse.getLast());
//                // downLoadApp(checkUpdateResponse.getUrl());
            }
        };
        RxHelper.bindOnUIActivityLifeCycle(checkUpdateResponseObservable, checkUpdateResponseCommonDialogObserver, MainNewActivity.this);
    }


    private void showNoticeDialog(String version_info) {
        // 构造对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("更新提示");
        builder.setMessage(version_info);
        // 更新
        builder.setPositiveButton("立即更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                NotificationManagerCompat manager = NotificationManagerCompat.from(VsdApplication.getContext());
                boolean isOpened = manager.areNotificationsEnabled();
                if (!isOpened) {
                    warningNotifyDialog("请开启通知权限，以查看下载进度");
                }
                SimpleToast.toastMessage("将为您后台下载", Toast.LENGTH_SHORT);
                //开启下载apk的IntentService
                Intent intent = new Intent(mContext, DownloadIntentService.class);
                startService(intent);
            }
        });
        // 稍后更新
        builder.setNegativeButton("以后更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();

            }
        });
        Dialog noticeDialog = builder.create();
        noticeDialog.show();
    }




    protected void warningNotifyDialog(String message) {
        new AlertDialog.Builder(mContext)
                .setTitle(getResources().getString(R.string.notice))
                .setMessage(message)
                .setPositiveButton(getResources().getString(R.string.sure), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        //去开启通知权限
                        goToNotificationSettings();

                    }
                })
                .setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                })
                .create().show();

    }

    public void goToNotificationSettings() {
        Intent i = new Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
        i.putExtra(Settings.EXTRA_APP_PACKAGE, getPackageName());
        startActivity(i);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bni1:
                setClick(0);
                addFragmentNotToStack(R.id.search_edit_frame, homeFragment);
                break;
            case R.id.bni2:
                setClick(1);
                addFragmentNotToStack(R.id.search_edit_frame, new MessageFragment());
                break;
            case R.id.bni3:
                setClick(2);
                addFragmentNotToStack(R.id.search_edit_frame, new EnterpriseHomeFragment());
                break;
            case R.id.tv_header:
                toActivity(UserInfoActivity.class);

                break;
            default:
                break;
        }


    }

    @Override
    protected void onResume() {
        super.onResume();
        //头像更换后的加载，
        loadImage(mContext, ivHeader, UserData.getUserInfo().getHeadImg());

    }

    @Override
    protected void initViewEvent() {

    }

    //glide加载头像
    protected void loadImage(Context mContext, ImageView imageView, String url) {

        RequestOptions options = new RequestOptions()
                .placeholder(R.drawable.ic_person_header)
                .error(R.drawable.ic_person_header)
                .fallback(R.drawable.ic_person_header)
                .override(com.bumptech.glide.request.target.Target.SIZE_ORIGINAL);
        Glide.with(mContext)
                .load(url)
                .apply(options)
                .into(imageView);

    }
}
